package com.gis.halodepok;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;

import com.gis.halodepok.R;
public class Moneychanger extends ListActivity {
public static final int MENU_CALL=1;
public static final int MENU_GPS=2;
public static final int MENU_BUKA=3;


	
	@Override
	public boolean onContextItemSelected(MenuItem menu) {
		AdapterContextMenuInfo info=(AdapterContextMenuInfo) menu.getMenuInfo();
	    int pos=info.position;
	    Item item=((AdapterItem)getListView().getAdapter()).getList()[pos];
		int menuid=menu.getItemId();
		if (menuid==MENU_CALL){
			Intent intent=new Intent (Intent.ACTION_DIAL,Uri.parse("tel:"+item.getTelp()));
			startActivity(intent);
		}
		else if (menuid==MENU_GPS){
//			
			Intent intent=new Intent (Intent.ACTION_VIEW,Uri.parse("http://maps.google.com/?f=d&saddr=&daddr="+item.getLat()+","+item.getLon()+" ("+item.getNama()+")"));
			startActivity(intent);
		}
		else if (menuid==MENU_BUKA){
			 AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
             
	            // set the message to display
	            alertbox.setMessage(item.getBuka());
	             
	            // add a neutral button to the alert box and assign a click listener
	            alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
	                 
	                // click listener on the alert box
	                public void onClick(DialogInterface arg0, int arg1) {
	                   
	                }
	            });
	             
	            // show it
	            alertbox.show();
		}
	
				
		// TODO Auto-generated method stub
		return super.onContextItemSelected(menu);
	}


	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(Menu.NONE,MENU_CALL,Menu.NONE,"Telepon");
		menu.add(Menu.NONE,MENU_GPS,Menu.NONE,"Navigasi");
		menu.add(Menu.NONE,MENU_BUKA,Menu.NONE,"Jam Buka");
	}



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		Item[] list=new Item[6];
//		list[0]= new Item ("T$V Money Changer","Jl.Margonda Raya No.222 A (Seberang Bank Mandiri)","02177210646","Senin-Minggu \n08.30-18.00", -6.385013,106.828448);
//		list[1]= new Item ("T$V Money Changer","Mini Market Koperasi Teratai Brimob Kelapa Dua, Jl.Akses UI","02187715169","Senin-Minggu \n09.30-18.00 \n\nSabtu \n09.00-17.00", -6.355371,106.852459);
//		list[2]= new Item ("Sentral Utama Valasindo 1","Jl. Margonda raya no.184 A (Depan mall depok)","0217521693","Senin-Jum'at \n10.00-19.00 \nSabtu-Minggu \n10.00-17.00", -6.387338,106.827568);	
//		list[3]= new Item ("Sentral Utama Valasindo 2","Depok Town Center Lt I blok B No.34","02177886191","Senin-Jum'at \n10.00-19.00 \nSabtu-Minggu \n10.00-17.00", -6.394998,106.793201);
//		list[4]= new Item ("Defidatama Bintang Artha","Cinere Mall Lt Dasar  No.128","0217545104","Senin-Minggu \n09.15-19.00", -6.323856,106.783919);
//		list[5]= new Item ("Ananda Money Changer","Depok Town Square, Lt. Dasar Blok GS 26 No.6","081314739062","Senin-Minggu \n12.00-20.00", -6.372517,106.832774);
		
		ArrayList<Item> items = readfilexml();
		Item[] list=new Item[items.size()];
		for (int i = 0; i < items.size(); i++) {
			list[i] = items.get(i);
		}
		
		LocationManager manager= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location networklocation= manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		Location gpslocation= manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		Location  mylocation=null;
		if (networklocation!=null)
		{ 
			mylocation=networklocation;
		    if (gpslocation!=null && gpslocation.getTime()> networklocation.getTime())
		    { 
		    	mylocation=gpslocation;
		    }
		}
		else if (gpslocation !=null)
		{
			mylocation=gpslocation;
		}
		setContentView(R.layout.listmenu);
		AdapterItem adapter=new AdapterItem (this,R.layout.list,list,mylocation);
		setListAdapter(adapter);
		((AdapterItem)adapter).sortByNameAsc();
		registerForContextMenu(getListView());
	}


	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) { 
	    openContextMenu(v);
	}

	
	static final String KEY_ITEM = "item"; // parent node
	static final String KEY_NAMA = "nama";
	static final String KEY_ALAMAT = "alamat";
	static final String KEY_BUKA = "buka";
	static final String KEY_TELP = "telp";
	static final String KEY_LAT = "lat";
	static final String KEY_LONG = "long";

	public Document getDomElement(String xml) {
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			doc = db.parse(is);

		} catch (ParserConfigurationException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (SAXException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		}
		// return DOM
		return doc;
	}
	
	public String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return this.getElementValue(n.item(0));
	}

	public final String getElementValue(Node elem) {
		Node child;
		if (elem != null) {
			if (elem.hasChildNodes()) {
				for (child = elem.getFirstChild(); child != null; child = child
						.getNextSibling()) {
					if (child.getNodeType() == Node.TEXT_NODE) {
						return child.getNodeValue();
					}
				}
			}
		}
		return "";
	}
	
	
	public ArrayList<Item> readfilexml(){
		ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
		ArrayList<Item> items = new ArrayList<Item>();
        Document doc = getDomElement(readFromFile());
 
        NodeList nl = doc.getElementsByTagName(KEY_ITEM);
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
           
            Item item = new Item(getValue(e, KEY_NAMA), getValue(e, KEY_ALAMAT), getValue(e, KEY_TELP),getValue(e, KEY_BUKA), Double.parseDouble(getValue(e, KEY_LAT)), Double.parseDouble(getValue(e, KEY_LONG)));
            items.add(item);
            
           
            
            map.put(KEY_NAMA, getValue(e, KEY_NAMA));
            map.put(KEY_ALAMAT, getValue(e, KEY_ALAMAT));
            map.put(KEY_TELP, getValue(e, KEY_TELP));
            map.put(KEY_BUKA, getValue(e, KEY_BUKA));
            map.put(KEY_LAT, getValue(e, KEY_LAT));
            map.put(KEY_LONG, getValue(e, KEY_LONG));
            
            // adding HashList to ArrayList
            System.err.println(map.get(KEY_NAMA)+"|"+map.get(KEY_ALAMAT));
            menuItems.add(map);
        }
        return items;
	}
	private String readFromFile() {

		String ret = "";

		try {
			File root = Moneychanger.this.getDir("haha", Context.MODE_PRIVATE);

			File dir = new File(root.getAbsolutePath() + "/xmls/16.xml");
			FileInputStream inputStream = new FileInputStream(dir);
			if (inputStream != null) {
				InputStreamReader inputStreamReader = new InputStreamReader(
						inputStream);
				BufferedReader bufferedReader = new BufferedReader(
						inputStreamReader);
				String receiveString = "";
				StringBuilder stringBuilder = new StringBuilder();

				while ((receiveString = bufferedReader.readLine()) != null) {
					stringBuilder.append(receiveString);
				}

				inputStream.close();
				ret = stringBuilder.toString();
			}
		} catch (FileNotFoundException e) {
			Log.e("login activity", "File not found: " + e.toString());
		} catch (IOException e) {
			Log.e("login activity", "Can not read file: " + e.toString());
		}

		return ret;
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
